<?php
use com\gdl\common\dataobject\common\ResultDO; 
use com\gdl\newagk\interfaces\QbankServiceIf;
use com\gdl\newagk\dataobject\qbank\QbankDTO; 
require(dirname(dirname(__FILE__)) ."/php_sdk-master/include.php");
use MagicCrypt\MagicCrypt;
/**
 * 题库App接口 
 * 包含列表 详情
 */
class api_QbankService extends api_Abstract implements QbankServiceIf{ 
    /**
     * 题库列表
     */
    public function qbankList(QbankDTO $qbank)
    { 
        $platformId = $qbank->id ? gdl_lib_BaseUtils::getStr($qbank->id) : "";
        $data = $qbank->data ? $qbank->data : "";
        $identity_id =  $qbank->identity_id ? gdl_lib_BaseUtils::getStr($qbank->identity_id, 'int') : 0;
		$adminReg = $qbank->filed ? $qbank->filed : "";
		$offset = $qbank->offset ? $qbank->offset : 0;
		$num = $qbank->num ? $qbank->num : 10;
		$result = new ResultDO();
        $result->success = true;
		$result->message = "没有更多数据了";
        $result->code = 400; 
        $result->data = [];
		# 分页
		if($offset=='0') $offset=1;
		$rows = $num;
		$limit = ($offset - 1) * $rows . "," . $rows;
		$group = 'order by sort desc limit '.$limit;		
		if(empty($platformId) || empty($identity_id)){
			$result->message = "缺少必要参数";
			return $result;
		}
		
        try{
			$qbankModel = new model_newagk_qbank();
			$qbankTagModel = new model_newagk_qbanktag();
			$praModel = new model_newagk_pracitice();
			$collectModel = new model_newagk_collection();
			$condition = "isdelete = 0 and total<>0 and status=1 and admin_reg in ('{$adminReg}') ";
			
			if(!empty($data['name'])){
				$condition .= " and name like '%".$data['name']."%'";
			}
			
			# 如果选择全部单传tag ，如果选择个别则不传只传子分类id
			if(!empty($data['tag'])){
				$tagArray = explode(",",$data['tag']);
				$sqlStr = " ";
				
				for($i=0; $i<count($tagArray); $i++){
					if($i==count($tagArray)-1){
						$sqlStr.= " qbankTag like '%".$tagArray[$i]."%'";
					}else{
						$sqlStr.= " qbankTag like '%".$tagArray[$i]."%' or ";
					} 
				}
				if(!empty($data['tagVal'])){
					$condition.= " and (".$sqlStr." or "; 
				}else{
					$condition.= " and (".$sqlStr.") "; 
				}
			}
			//var_dump($condition);exit;
			# 赛选子分类
			if(!empty($data['tagVal'])){
				$tagValArray = explode(",",$data['tagVal']);
				$sqlValStr = "";
				for($i=0; $i<count($tagValArray); $i++){
					if($i==count($tagValArray)-1){
						$sqlValStr.= " qbankTagValue like '%".$tagValArray[$i]."%'";
					}else{
						$sqlValStr.= " qbankTagValue like '%".$tagValArray[$i]."%' or ";
					} 
				}
				if(!empty($data['tag'])){
					$condition.= " ".$sqlValStr.") "; 
				}else{
					$condition.= " and (".$sqlValStr.") "; 
				}
			}
			$filed = "id,name,platformId,status,issharing,FROM_UNIXTIME(updateTime, '%Y年%m月%d日') as update_time,sort,total,thumb";
			$list = $qbankModel->select($condition,$filed, $group)->items;
			//var_dump($qbankModel);exit;
			# 预留做了多少题
			# 重新统计试题
			$quesModel = new model_newagk_questions();
			$errorModel = new model_newagk_errorpracitice();
			for($i=0; $i<count($list); $i++){
				$list[$i]['errorCount'] = 0;
				$list[$i]['collectCount'] = 0;
				$pWhere = "qbankId=".$list[$i]['id']." and identityId=".$identity_id." and isdelete=0 and (type='special' or type='order')";
				$praNum = $praModel->select($pWhere,'count(id) as num')->items;
				$list[$i]['completeCount'] = $praNum[0]['num']?$praNum[0]['num']:0;
				if($praNum[0]['num']>$list[$i]['total']){
					$list[$i]['completeCount'] = $list[$i]['total'];
				}
				
				$total = $quesModel->selectOne('isdelete=0 and status=1 and qbankId='.$list[$i]['id'],'count(id) as nums');
				$list[$i]['total'] = $total['nums']?$total['nums']:$list[$i]['total'];
				# 计算是否有错题
				$errorCount = $errorModel->selectOne('isdelete=0 and identityId='.$identity_id.' and qbankId='.$list[$i]['id'], 'count(id) as nums');
				# 计算是否有收藏
				$collectCount = $collectModel->selectOne('isdelete=0 and identityId='.$identity_id.' and qbankId='.$list[$i]['id'], 'id,questionId,count(id) as nums');
				$list[$i]['errorCount'] = $errorCount['nums']?$errorCount['nums']:0;
				$list[$i]['collectCount'] = $collectCount['nums']?$collectCount['nums']:0;
			}
			if($list){
				$result->message = "获取成功";
				$result->code = 200;
				$result->data= $list;
			}else{
				$result->code = 200;
			}
			# 处理题库练习进度
			
                
        } catch (Exception $e) {
                $result->success = false;
                $result->code = $e->getCode();
                $result->message = $e->getMessage(); 
        }
        return $result; 
    }
	/**
	* 查找当前平台的标签
	*/
	public function qbankTag(QbankDTO $qbank){
		$platformId = $qbank->id ? gdl_lib_BaseUtils::getStr($qbank->id) : "";
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		if(empty($platformId)){
			$result->message = "请带入平台标识";
			return $result;
		}
		try{
			$qbankTagModel = new model_newagk_qbanktag();
			$condition = "platformId='{$platformId}' and isdelete=0 and  type=0";
			$filed = "id,pid,tagName";
			$tagList = $qbankTagModel->select($condition,$filed)->items;
			//var_dump($qbankTagModel);exit;
			$newList = $this->getTree($tagList,0);
			if($newList){
				$result->code = 200;
				$result->message = "获取成功";
				$result->data= $newList;
			}
		}catch(Exception $e){
			$result->success = false;
			$result->code = $e->getCode();
			$result->message = $e->getMessage(); 
		}
		return $result;
	}
    /**
     *  题库详情
     */
    public function qbankInfo(QbankDTO $qbank){ 
		$platformId = $qbank->id ? gdl_lib_BaseUtils::getStr($qbank->id) : "";
		$qbankId = $qbank->userid ? gdl_lib_BaseUtils::getStr($qbank->userid) : "";
		
		#用户identityId
		$identityId = $qbank->gdl_userid ? gdl_lib_BaseUtils::getStr($qbank->gdl_userid) : "";
		
		$result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data = [];
		$result->message = "暂无该题库详情";
		if(empty($qbank)){
			$result->message = "请带入题库标识";
			return $result;
		}
        try{
			$qbankModel = new model_newagk_qbank();
			$qbankTagModel = new model_newagk_qbanktag();
			$praModel = new model_newagk_pracitice();
			$collectModel = new model_newagk_collection();
			$condition = "isdelete =0 and id='{$qbankId}'";
			$filed = "id,name,remark,FROM_UNIXTIME(updateTime, '%Y年%m月%d日') as updateTime,total,thumb,qbankTag,qbankTagValue";
			$qbankInfo = $qbankModel->selectOne($condition, $filed);
			if($qbankInfo){
				$tagValArray = explode(",",$qbankInfo['qbankTagValue']);
				$tagStr = implode("','",$tagValArray);
				$tagList = $qbankTagModel->select("id in ('{$tagStr}')","tagName")->items;
				$newStrArray = [];
				foreach($tagList as $k){
					$newStrArray[] = $k['tagName'];
				}
				$qbankInfo['info'] = implode(",",$newStrArray) ? implode(",",$newStrArray) : '暂无标签'; 
				# 重新统计试题
				$quesModel = new model_newagk_questions();
				$errorModel = new model_newagk_errorpracitice();
				$total = $quesModel->selectOne('isdelete=0 and status=1 and qbankId='.$qbankId,'count(id) as nums');
				$qbankInfo['total'] = $total['nums']?$total['nums']:$qbankInfo['total'];
				
				$pWhere = "qbankId=".$qbankId." and identityId=".$identityId." and isdelete=0 and (type='special' or type='order')";
				$praNum = $praModel->select($pWhere,'count(id) as num')->items;
				$qbankInfo['completeCount'] = $praNum[0]['num']?$praNum[0]['num']:0; #目前做了多少题
				if($praNum[0]['num']>$qbankInfo['total']){ 
					$qbankInfo['completeCount'] = $qbankInfo['total'];
				}
				# 计算是否有错题
				$errorCount = $errorModel->selectOne('isdelete=0 and identityId='.$identityId.' and qbankId='.$qbankId, 'count(id) as nums');
				# 计算是否有收藏
				$collectCount = $collectModel->selectOne('isdelete=0 and identityId='.$identityId.' and qbankId='.$qbankId, 'count(id) as nums');
				$qbankInfo['errorCount'] = $errorCount['nums']?$errorCount['nums']:0;
				$qbankInfo['collectCount'] = $collectCount['nums']?$collectCount['nums']:0;
				
				$result->code = 200;
				$result->data[] = $qbankInfo;
				$result->message = "获取成功";
			}
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        return $result;
    }
	
	 /**
     *  顺序练习
     */
    public function qbankOrder(QbankDTO $qbank){ 
	$result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = [];
     
        try{
		 
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        return $result;
    }
	
	 /**
     *  qbankSpecial
     */
    public function qbankSpecial(QbankDTO $qbank){ 
	$result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = [];
     
        try{
		 
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        return $result;
    }
	
	 /**
     *  qbankWrong
     */
    public function qbankWrong(QbankDTO $qbank){ 
	$result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = [];
     
        try{
		 
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        return $result;
    }
	
	 /**
     *  qbankChapter
     */
    public function qbankChapter(QbankDTO $qbank){ 
	$result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = [];
     
        try{
		 
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        return $result;
    }
	
	/**
     *  qbankCollection
     */
    public function qbankCollection(QbankDTO $qbank){ 
	$result = new ResultDO();
        $result->code = 400;
        $result->success = true;
        $result->data[] = [];
     
        try{
		 
        } catch (Exception $e) {
            $result->success = false;
            $result->code = $e->getCode();
            $result->message = $e->getMessage(); 
        }
        return $result;
    }
	/**
	*  找儿子
	*/
	public static function getTree($data, $pId){
		$tree = '';
		foreach($data as $k => $v)
		{
		  if($v['pid'] == $pId)
		  {        //父亲找到儿子
		   $v['pid'] = self::getTree($data, $v['id']);
		   $tree[] = $v;
		   //unset($data[$k]);
		  }
		}
		return $tree;
	}
     
   
}
